import React, { Component, ComponentClass } from 'react';
import {View, Navigator} from '@tarojs/components'
import {connect} from 'react-redux'
import {CityLocation, PlatformSet, CategoryListPageGood, SubCategory} from '../../utils/server.interface'
import {AtSearchBar} from 'taro-ui'
import {platform} from '../../utils/platform-settting.service'
import GoodShow from '../../components/good-show/good-show'
import {http} from '../../utils/http'
import {CATEGORY_SCENIC_PAGE, LIST_CATEGORY} from '../../constants/api'
import SubCategoryComponent from '../components/sub-category/sub-category-component'
import {newHttp} from "../../utils/request";
import {GetRequest, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './category-list.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  searchText: string
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  platformSet: PlatformSet
  goods: CategoryListPageGood[]
  categoryId: number
  subCategory: SubCategory[]
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface CategoryList {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class CategoryList extends Component {
  state: PageState = {
    searchText: '',
    loadMoreStatus: 'loading',
    platformSet: {isShowServicePhone: 1, platformName: '', platformServicePhone: '', platformSellerType: 0},
    goods: [],
    categoryId: 0,
    subCategory: [],
  }
  page = 1

  async componentDidShow() {
    vcmonitor(this);
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const categoryId = parseInt(Taro.getCurrentInstance().router.params.category) || 0
    this.setState({categoryId}, async () => {
      const platformSet = await platform.getSetting()
      const goods = await this.getGoods(this.page)
      const categoryData = (await http.get<SubCategory[]>(LIST_CATEGORY, {c: categoryId})) || []

      if (platformSet) {
        this.setState({platformSet, goods, subCategory: categoryData})
      } else {
        this.setState({goods, subCategory: categoryData})
      }
    })
  }

  async getGoods(page = 1) {
    const goodsData = await newHttp.catchGet<CategoryListPageGood[]>(CATEGORY_SCENIC_PAGE, {
      areaId: this.props.location.region_id,
      p: page,
      k: this.state.searchText,
      c: this.state.categoryId
    })
    if (goodsData) {
      if (goodsData.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return goodsData
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async searchClick() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page)
      this.setState({goods})
    })
  }

  searchClear() {
    this.page = 1
    this.setState({searchText: '', loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page)
      this.setState({goods})
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods
      this.page++
      const newData = await this.getGoods(this.page)
      this.setState({goods: [...old, ...newData]})
    }
  }

  inputChange(value) {
    this.setState({searchText: value})
  }

  subCategoryClick(id) {
    this.setState({categoryId: id, loadMoreStatus: 'loading', goods: []}, async () => {
      this.page = 1
      const goods = await this.getGoods(this.page)
      this.setState({goods})
    })
  }

  render() {
    const {searchText, loadMoreStatus, goods, subCategory, categoryId} = this.state
    const subCategoryConvert = subCategory.map(item => ({
      name: item.name,
      id: item.id,
      url: item.link,
      urlType: item.link_type
    }))
    return (
      <View className='category-list-root'>
        <GzhAuth />
        <View className='search-box'><AtSearchBar value={searchText} placeholder='搜索'
          onClear={this.searchClear.bind(this)}
          onActionClick={this.searchClick.bind(this)}
          onChange={this.inputChange.bind(this)}
        /></View>
        {subCategory.length > 0 && <SubCategoryComponent activeId={categoryId} data={subCategoryConvert}
          onChange={this.subCategoryClick.bind(this)}
        />}
        {goods.length > 0 && <View className='goods-box'>
          {goods.map(item => <Navigator className='good-item' url='' key={item.id} hoverClass='none'>
            <GoodShow image={item.img} title={item.name} price={item.price} markPrice={item.market_price} />
          </Navigator>)}
        </View>}
      </View>
    )
  }
}

export default CategoryList as ComponentClass<PageOwnProps, PageState>
